package com.bdcom.dialog;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bdcom.comp.ToolBarPanel;
import com.bdcom.model.DeviceType;
import com.bdcom.repository.DeviceTypeRepository;
import com.bdcom.util.PlannerUtil;

@Component
public class DeviceTypeCfgDialog extends JDialog implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTable jtable;

	private DefaultTableModel dtm;

	private List<DeviceType> typeList;

	private JPanel panel;

	private JPanel frebandpanel;

	private JTabbedPane tabpanel;

	private JCheckBox checkbox24;

	private JCheckBox checkbox50;

	private FormPanel panel24;

	private FormPanel panel50;

	private JButton newBtn;

	private JButton delBtn;

	private JButton saveBtn;

	private JButton freshBtn;
	@Autowired
	private DeviceTypeRepository deviceTypeRepository;

	public DeviceTypeCfgDialog() {
		super();
		// TODO Auto-generated constructor stub
		setLayout(new BorderLayout());

		setSize(400, 360);

		dtm = new DefaultTableModel(PlannerUtil.DEVICE_TAB_HEADER, 0);

		jtable = new JTable(dtm);

		jtable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				// TODO Auto-generated method stub

				int selected = jtable.getSelectedRow();

				if (selected < typeList.size() && selected > -1) {
					setValue(typeList.get(selected));
				}
			}

		});

		JScrollPane scroll = new JScrollPane(jtable);

		scroll.setPreferredSize(new Dimension(0, 100));
		
		add(scroll, BorderLayout.NORTH);

		panel = new JPanel();

		panel.setLayout(new BorderLayout());

		frebandpanel = new JPanel();

		frebandpanel.add(new JLabel(PlannerUtil.getString("frequency bandwidth")));

		checkbox24 = new JCheckBox("2.4G");

		frebandpanel.add(checkbox24);

		checkbox50 = new JCheckBox("5G");

		frebandpanel.add(checkbox50);

		panel.add(frebandpanel, BorderLayout.NORTH);

		tabpanel = new JTabbedPane();

		panel24 = new FormPanel();

		panel50 = new FormPanel();

		tabpanel.add("2.4G", panel24);

		tabpanel.add("5.0G", panel50);

		panel.add(tabpanel, BorderLayout.CENTER);

		add(panel, BorderLayout.CENTER);
		
		JPanel btnpanel = new JPanel();

		btnpanel.add(newBtn = new JButton(PlannerUtil.getString("add")));

		newBtn.addActionListener(this);

		newBtn.setActionCommand("new");

		btnpanel.add(delBtn = new JButton(PlannerUtil.getString("delete")));

		delBtn.addActionListener(this);

		delBtn.setActionCommand("del");

		btnpanel.add(saveBtn = new JButton(PlannerUtil.getString("save")));

		saveBtn.addActionListener(this);

		saveBtn.setActionCommand("save");

		btnpanel.add(freshBtn = new JButton(PlannerUtil.getString("refresh")));

		freshBtn.addActionListener(this);

		freshBtn.setActionCommand("refresh");

		add(btnpanel,BorderLayout.SOUTH);

		setTitle(PlannerUtil.getString("deviceConfiguration"));

		setModal(true);

		setResizable(false);

		setLocationRelativeTo(null);

		setDefaultCloseOperation(HIDE_ON_CLOSE);

	}

	private void setValue(DeviceType deviceType) {
		// TODO Auto-generated method stub

		if (deviceType == null) {
			return;
		}

		checkbox24.setSelected(deviceType.isEnable2gFrequencyBandwidth());

		checkbox50.setSelected(deviceType.isEnable5gFrequencyBandwidth());

		panel24.bandwidth_combobox.setSelectedItem(deviceType.getBandWidth2g());

		panel24.channel_combobox.setSelectedItem(deviceType.getChannel2g());

		panel24.power_tfd.setValue(deviceType.getPower2g());

		panel24.protocol_combobox.setSelectedItem(deviceType.getProtocol2g());

		panel24.ssid_tfd.setText(deviceType.getSsid2g());

		panel24.wirelessgain_tfd.setValue(deviceType.getWirelessGain2g());

		panel50.bandwidth_combobox.setSelectedItem(deviceType.getBandWidth5g());

		panel50.channel_combobox.setSelectedItem(deviceType.getChannel5g());

		panel50.power_tfd.setValue(deviceType.getPower5g());

		panel50.protocol_combobox.setSelectedItem(deviceType.getProtocol5g());

		panel50.ssid_tfd.setText(deviceType.getSsid5g());

		panel50.wirelessgain_tfd.setValue(deviceType.getWirelessGain5g());
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub

		String command = e.getActionCommand();

		if ("new".equals(command)) {

			newDType();

		} else if ("save".equals(command)) {

			saveDType();

		} else if ("del".equals(command)) {

			delDtype();

		} else if ("refresh".equals(command)) {

			loadTypes();
		}

	}

	private void delDtype() {
		// TODO Auto-generated method stub
		int selected = jtable.getSelectedRow();

		if (selected == -1) {

			JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please choose one"));

			return;
		}

		int result = JOptionPane.showConfirmDialog(null, PlannerUtil.getString("Yes or No"));

		if (result == JOptionPane.OK_OPTION) {
			/**
			 * 如果在设备类型model中存在，需要修改文件。
			 * 
			 * 若不存在，仅仅删除表中的数据。
			 * 
			 */

			if (selected < typeList.size()) {
				deviceTypeRepository.delete(typeList.get(selected));
				loadTypes();
			} else {
				dtm.removeRow(selected);
			}
		}
	}

	private void saveDType() {
		// TODO Auto-generated method stub
		if (jtable.isEditing()) {

			JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please finish editing"));

			return;
		}

		int row = jtable.getSelectedRow();

		if (row == -1) {

			JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please choose one"));

			return;
		}

		if (dtm.getValueAt(row, 0).toString().equals("")) {
			JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please input type name"));
			return;
		}

		if (!panel24.verify()) {
			return;
		}

		if (!panel50.verify()) {
			return;
		}

		String typeName = dtm.getValueAt(row, 0).toString();

		DeviceType dt = new DeviceType();

		dt.setTypeName(typeName);

		dt.setEnable2gFrequencyBandwidth(checkbox24.isSelected());

		dt.setEnable5gFrequencyBandwidth(checkbox50.isSelected());

		dt.setChannel2g((int) panel24.channel_combobox.getSelectedItem());

		dt.setChannel5g((int) panel50.channel_combobox.getSelectedItem());

		dt.setSsid2g(panel24.ssid_tfd.getText());

		dt.setSsid5g(panel50.ssid_tfd.getText());

		dt.setBandWidth2g((int) panel24.bandwidth_combobox.getSelectedItem());

		dt.setBandWidth5g((int) panel50.bandwidth_combobox.getSelectedItem());

		dt.setPower2g(Integer.parseInt(panel24.power_tfd.getText()));

		dt.setPower5g(Integer.parseInt(panel50.power_tfd.getText()));

		dt.setProtocol2g(panel24.protocol_combobox.getSelectedItem().toString());

		dt.setProtocol5g(panel50.protocol_combobox.getSelectedItem().toString());

		dt.setWirelessGain2g(Integer.parseInt(panel24.wirelessgain_tfd.getText()));

		dt.setWirelessGain5g(Integer.parseInt(panel50.wirelessgain_tfd.getText()));
		// 保存类型
		deviceTypeRepository.save(dt);

		loadTypes();
	}

	private void newDType() {
		// TODO Auto-generated method stub
		dtm.addRow(new Object[] { "" });

		jtable.setRowSelectionInterval(dtm.getRowCount() - 1, dtm.getRowCount() - 1);

	}

	class FormPanel extends JPanel {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		private JComboBox<Integer> channel_combobox;

		private JTextField ssid_tfd;

		private JFormattedTextField power_tfd;

		private JComboBox<Integer> bandwidth_combobox;

		private JComboBox<String> protocol_combobox;

		private JFormattedTextField wirelessgain_tfd;

		public FormPanel() {
			super();
			// TODO Auto-generated constructor stub
			GridBagLayout glayout = new GridBagLayout();

			setLayout(glayout);
			
			GridBagConstraints constraints=new GridBagConstraints();
			
			constraints.insets=new Insets(5,0,0,10);

			constraints.fill=GridBagConstraints.HORIZONTAL;

			constraints.gridx=0;
			
			add(new JLabel(PlannerUtil.getString("channel")),constraints);

			channel_combobox = new JComboBox<>();

			channel_combobox.addItem(1);
			channel_combobox.addItem(2);
			channel_combobox.addItem(3);
			channel_combobox.addItem(4);

			constraints.gridx=1;
					
			add(channel_combobox,constraints);

			constraints.gridx=2;
			
			add(new JLabel("SSID"),constraints);

			ssid_tfd = new JTextField(7);
			
			constraints.gridx=3;
			
			add(ssid_tfd,constraints);

			constraints.gridx=0;
			
			add(new JLabel(PlannerUtil.getString("power")),constraints);

			power_tfd = new JFormattedTextField(new java.text.DecimalFormat("#0"));
			// 设置默认的功率
			power_tfd.setValue(10);

			constraints.gridx=1;
			
			add(power_tfd,constraints);

			constraints.gridx=2;
			
			add(new JLabel(PlannerUtil.getString("bandwidth")),constraints);

			bandwidth_combobox = new JComboBox<>();

			bandwidth_combobox.addItem(20);
			bandwidth_combobox.addItem(40);

			constraints.gridx=3;
			
			add(bandwidth_combobox,constraints);

			constraints.gridx=0;
			
			add(new JLabel(PlannerUtil.getString("protocol")),constraints);

			protocol_combobox = new JComboBox<>();

			protocol_combobox.addItem("802.11g");
			protocol_combobox.addItem("802.11b");
			protocol_combobox.addItem("802.11n");

			constraints.gridx=1;
			
			add(protocol_combobox,constraints);

			constraints.gridx=2;
			
			add(new JLabel(PlannerUtil.getString("wirelessgain")),constraints);

			wirelessgain_tfd = new JFormattedTextField(new java.text.DecimalFormat("#0"));
			// 设置默认值
			wirelessgain_tfd.setValue(0);

			constraints.gridx=3;
			
			add(wirelessgain_tfd,constraints);

		}

		/**
		 * 验证表单中的数据是否合法
		 * 
		 * @return
		 */
		boolean verify() {

			if (ssid_tfd.getText() == null || "".equals(ssid_tfd.getText())) {
				JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please input the ssid"));

				return false;
			}
			if (power_tfd.getValue() == null) {

				JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please input the power"));

				return false;
			}
			if (wirelessgain_tfd.getValue() == null) {
				JOptionPane.showMessageDialog(null, PlannerUtil.getString("Please input the wirelessgain"));

				return false;
			}

			return true;
		}
	}

	@PostConstruct
	private void loadTypes() {
		// TODO Auto-generated method stub
		typeList = deviceTypeRepository.findAll();
		removeTypes();
		for (DeviceType deviceType : typeList) {
			dtm.addRow(new Object[] { deviceType.getTypeName() });
			ToolBarPanel.devCombobox.addItem(deviceType);
		}
	}

	private void removeTypes() {
		// TODO Auto-generated method stub
		int i = dtm.getRowCount() - 1;

		for (; i > -1; i--) {
			dtm.removeRow(i);
		}
		ToolBarPanel.devCombobox.removeAllItems();

	}

}
